//
//  SubTableView.m
//  SubTableExample
//
//  Created by Alex Koshy on 7/16/14.
//  Copyright (c) 2014 ajkoshy7. All rights reserved.
//

#import "SubTableView.h"
//#import "SubTableViewCell.h"


@implementation SubTableView

@synthesize insideTableView;

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        
        [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        [[self contentView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
        //        NSString *str1=[NSString stringWithFormat:@"%d",TARGET_VERSION];
        //        if ([str1 isEqualToString:@"4"]||[str1 isEqualToString:@"14"]||[str1 isEqualToString:@"6"]||[str1 isEqualToString:@"16"]) {//
        //            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"P006Home" ofType:@"plist"];
        //            NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
        //            parentArray= [[dictionary objectForKey:@"HomeSlider"] objectForKey:@"ParentTextArray"];
        //            subArray=[[dictionary objectForKey:@"HomeSlider"] objectForKey:@"SubTextArray"];
        //            //        fgColor = [UIColor colorWithRed:150/255 green:150/255 blue:150/255 alpha:1.0];
        //            //        bgColor = [UIColor clearColor];
        //            font = [UIFont systemFontOfSize:14.0];
        //            [self configureInsideTableView];
        //
        //
        //        }else{
        //
        //            NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"P009Home" ofType:@"plist"];
        //            NSDictionary *dictionary = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
        //            parentArray= [[dictionary objectForKey:@"HomeSlider"] objectForKey:@"ParentTextArray"];
        //            subArray=[[dictionary objectForKey:@"HomeSlider"] objectForKey:@"SubTextArray"];
        //            //        fgColor = [UIColor colorWithRed:150/255 green:150/255 blue:150/255 alpha:1.0];
        //            //        bgColor = [UIColor clearColor];
        //            font = [UIFont systemFontOfSize:14.0];
        //            [self configureInsideTableView];
        //
        //
        //        }
        font = [UIFont systemFontOfSize:14.0];
        [self configureInsideTableView];
        
    }
    return self;
}



#pragma mark - Configuration

- (void)configureInsideTableView {
    
    self.insideTableView = [[UITableView alloc] init];
    insideTableView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, self.contentView.frame.size.height);
    
    insideTableView.dataSource = self;
    insideTableView.delegate = self;
    
    [self.insideTableView setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
    insideTableView.scrollEnabled = NO;
    
    insideTableView.backgroundColor = [UIColor clearColor];
    insideTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    //insideTableView.separatorColor = [UIColor colorWithWhite:( 70/255.0) alpha:1.0];
    [insideTableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [self.contentView addSubview:self.insideTableView];
}



#pragma mark - Getters/Setters

/***
 * Delegate
 */
- (id)getDelegate {
    return delegate;
}
// TODO combine set delegate and parentIndex into one method for better safety
- (void)setDelegate:(id<SubTableViewCellDelegate>)deleg {

    delegate = deleg;
    NSInteger numberOfChild = [delegate numberOfChildrenUnderParentIndex:self.parentIndex];
    
    NSInteger rowHeight = [delegate heightForChildRows];
    insideTableView.frame = CGRectMake(0, 0, self.contentView.frame.size.width, rowHeight * numberOfChild);
    
    //    NSString * parentIndexStr=[NSString stringWithFormat:@"%ld",(long)self.parentIndex];
    parentIndexKeyStr=[NSString stringWithFormat:@"parent%ld",(long)self.parentIndex];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    
    NSLog(@"%@", [userDefaults objectForKey:parentIndexKeyStr]);
    if ([userDefaults objectForKey:parentIndexKeyStr]) {
        addOrSubTractDict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentIndexKeyStr]];
        addOrSubtractArray=[NSMutableArray arrayWithArray:[addOrSubTractDict objectForKey:@"addOrSubtractARRAY"]];
        
    } else {
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSMutableArray* itemsArray =[[NSMutableArray alloc]init];
        NSMutableArray*menus = [user objectForKey:@"menus"];
        if (menus.count>0) {
            for (NSDictionary* dic in menus ){
                [itemsArray addObject: [dic objectForKey:@"funName"]];
            }
        }
   
        for (int j=0; j<itemsArray.count; j++) {
            NSMutableDictionary *dict=[[NSMutableDictionary alloc] init];
            NSMutableArray *arr=[NSMutableArray array];
            NSString *parentKeyStr=[NSString stringWithFormat:@"parent%ld",(long)j];
            NSInteger childCount = [delegate numberOfChildrenUnderParentIndex:j];
            
            for (int i=0; i<childCount; i++) {
                
                NSString *isDisplay=[NSString stringWithFormat:@"%@",  [[[[menus objectAtIndex: j]objectForKey:@"childrens" ]objectAtIndex:i]objectForKey:@"isDisplay"]];
                if ([isDisplay isEqualToString:@"1"]) {
                    [arr addObject:@"Y"];
                    
                }else{
                    
                    [arr addObject:@"N"];
                }
                
                
            }
            [dict setValue:arr forKey:@"addOrSubtractARRAY"];
            [userDefaults setObject:dict forKey:parentKeyStr];
            
            [[NSUserDefaults standardUserDefaults] synchronize];
        }
        
        addOrSubTractDict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentIndexKeyStr]];
        addOrSubtractArray=[NSMutableArray arrayWithArray:[addOrSubTractDict objectForKey:@"addOrSubtractARRAY"]];
    }
    
}

- (void)resetDefaults {
    NSUserDefaults * defs = [NSUserDefaults standardUserDefaults];
    NSDictionary * dict = [defs dictionaryRepresentation];
    for (id key in dict) {
        for ( int i=0; i<parentArray.count; i++) {
            NSString *parentKeyStr= [NSString stringWithFormat:@"parent%ld",(long)i];
            if ([key isEqualToString:parentKeyStr]) {
                [defs removeObjectForKey:key];
            }
        }
        
    }
    [defs synchronize];
}
- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];
}
- (void)reload {
    [self.insideTableView reloadData];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSInteger count= [self.delegate numberOfChildrenUnderParentIndex:self.parentIndex];
    if (count > 0)
        return count;
    else
        return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //static NSString *CELL_IDENTIFIER = @"SubTableViewCell_Reuse_Id";
    
    static NSString * const SecondLevelTableViewCellIdentifier = @"subNewTableViewCell";
    subNewTableViewCell *cell=(subNewTableViewCell *)[tableView dequeueReusableCellWithIdentifier:SecondLevelTableViewCellIdentifier];
    if (cell==nil) {
        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"subNewTableViewCell" owner:self options:nil];
        cell = [array objectAtIndex:0];
    }
    cell.delegate=self;
    
    NSInteger row = [indexPath row];
    cell.titleLable.text = [self.delegate titleLabelForChildIndex:row underParentIndex:self.parentIndex];
    [cell.iconImageView setImage:[self.delegate iconForCellAtChildIndex:row underParentIndex:self.parentIndex]];
    cell.addOrSubtractBtn.tag=indexPath.row;
    if ([[addOrSubtractArray objectAtIndex:indexPath.row] isEqualToString:@"N"]) {
        
        UIImage *img=[UIImage imageNamed:@"tianjia_new"];
        UIImage *tinted = [img rt_tintedImageWithColor:[UIColor colorWithRed:82.0/255.0 green:180.0/255.0 blue:236.0/255.0 alpha:1.0] ];
        [cell.addOrSubtractBtn setImage:tinted forState:UIControlStateNormal];
    } else {
        
        UIImage *img=[UIImage imageNamed:@"yitianjia_new"];
        UIImage *tinted = [img rt_tintedImageWithColor:[UIColor colorWithRed:146.0/255.0 green:207.0/255.0 blue:243.0/255.0 alpha:1.0] ];
        [cell.addOrSubtractBtn setImage:img forState:UIControlStateNormal];
    }
    return cell;
}

-(void)subAddOrSubtractBtnClick:(NSUInteger)tag {
    int num=0;
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    for ( int i=0; i<parentArray.count; i++) {
        NSString *parentKeyStr= [NSString stringWithFormat:@"parent%ld",(long)i];
        NSMutableDictionary *dict=[NSMutableDictionary  dictionaryWithDictionary:[userDefaults dictionaryForKey:parentKeyStr]];
        
        NSMutableArray *array=[NSMutableArray arrayWithArray:[dict objectForKey:@"addOrSubtractARRAY"]];
        for (int j=0; j<array.count; j++) {
            if ([[array objectAtIndex:j]isEqualToString:@"Y"]) {
                num++;
            }
        }
    }
  
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSMutableArray*menus = [user objectForKey:@"menus"];
    NSString *funIds=[NSString stringWithFormat:@"%@",  [[[[menus objectAtIndex:self.parentIndex] objectForKey:@"childrens"] objectAtIndex:tag] objectForKey:@"funId"]];
    NSString *str=[addOrSubtractArray objectAtIndex:tag];
    NSIndexPath *indexPath1= [NSIndexPath indexPathForRow:tag inSection:0];
    UITableViewCell *cell = [insideTableView cellForRowAtIndexPath:indexPath1];
    subNewTableViewCell *subCell=( subNewTableViewCell *)cell;
    if ([str isEqualToString:@"N"] ) {
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        
//        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObject:funIds];
        [param setValue:arr forKey:@"funIds"];
        [param setValue:@"1" forKey:@"isDisplay"];
        NSLog(@"param == %@", param);
        [HttpRequest requestData1:@"System/SetMenuDisplay" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            NSLog(@"rToken====%@",severDataDict.dataDict);
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self];
                    //str=@"Y";
                   // num++;
                    [subCell.addOrSubtractBtn setImage:[UIImage imageNamed:@"yitianjia_new"] forState:UIControlStateNormal];
                    // }
                    [addOrSubtractArray replaceObjectAtIndex:tag withObject:@"Y"];
                    [addOrSubTractDict setValue:addOrSubtractArray forKey:@"addOrSubtractARRAY"];
                    [userDefaults setObject:addOrSubTractDict forKey:parentIndexKeyStr];
                    
                    [userDefaults synchronize];
                    [self.delegate subTableviewCellSubtractOrAdd];
                }else{
                    [MBProgressHUD hideProgressHUDInternal:self];
                    [MBProgressHUD showTextHudSub:@"链接失败" view:self];
                }
            } else {
                [MBProgressHUD hideProgressHUDInternal:self];
                [MBProgressHUD showTextHudSub:@"链接失败" view:self];
            }
            
        }];
    } else if ([str isEqualToString:@"Y"] ) {
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
//        [param setValue:funIda forKey:@"funId"];
//        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        NSMutableArray *arr = [NSMutableArray array];
        [arr addObject:funIds];
        [param setValue:arr forKey:@"funIds"];
        [param setValue:@"0" forKey:@"isDisplay"];
        NSLog(@"%@", param);
        [HttpRequest requestData1:@"System/SetMenuDisplay" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            // NSLog(@"rToken====%@",severDataDict.dataDict);
            if (isSuccess) {
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [MBProgressHUD hideProgressHUDInternal:self];
                   // str=@"N";
                    //num--;
                    
                    UIImage *img=[UIImage imageNamed:@"tianjia_new"];
                    UIImage *tinted = [img rt_tintedImageWithColor:[UIColor colorWithRed:82.0/255.0 green:180.0/255.0 blue:236.0/255.0 alpha:1.0] ];
                    [subCell.addOrSubtractBtn setImage:tinted forState:UIControlStateNormal];
                    [addOrSubtractArray replaceObjectAtIndex:tag withObject:@"N"];
                    [addOrSubTractDict setValue:addOrSubtractArray forKey:@"addOrSubtractARRAY"];
                    [userDefaults setObject:addOrSubTractDict forKey:parentIndexKeyStr];
                    
                    [userDefaults synchronize];;
                    [self.delegate subTableviewCellSubtractOrAdd];
                }else{
                    [MBProgressHUD hideProgressHUDInternal:self];
                    [MBProgressHUD showTextHudSub:@"链接失败" view:self];
                }
                
            } else {
                [MBProgressHUD hideProgressHUDInternal:self];
                [MBProgressHUD showTextHudSub:@"链接失败" view:self];
                
            }
        }];
    }
}

#pragma mark - Table view delegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return [delegate heightForChildRows];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // must be implemented by concrete subclasses
    
    
}

@end
